/* Copyright (c) 2010 Sven Weidauer
 
 Permission is hereby granted,free of charge,to any person obtaining a copy of this software and associated documentation files (the "Software"),to deal in the Software without restriction,including without limitation the rights to use,copy,modify,merge,publish,distribute,sublicense,and/or sell copies of the Software,and to permit persons to whom the Software is furnished to do so,subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

#include <Platform/Threads.h>
#include <Platform/Locks.h>

#include <stdio.h>
#ifndef WINDOWS
#include <unistd.h>
#endif

#define PHILOSOPHER_COUNT 5

static MPLock chopsticks[PHILOSOPHER_COUNT];
static MPThread threads[PHILOSOPHER_COUNT];
static int timesEaten[PHILOSOPHER_COUNT] = { 0 };

static volatile bool running = true;

static void RandomSleep( int min, int max )
{
    unsigned long sleepTime = (min + ((unsigned long long)rand() * (max - min) / RAND_MAX));
#ifndef WINDOWS
	usleep( sleepTime * 1000 );
#else
	Sleep( sleepTime );
#endif
}

#ifdef WINDOWS
#define sleep(x) Sleep( (x) * 1000 )
#include <Platform/Locks.h>
static MPLock __printfLock;
static void InitPrintfLock()
{
    MPCreateLock( &__printfLock );
}
#define printf(...) do { MPAquireLock( __printfLock ); printf(__VA_ARGS__); MPReleaseLock( __printfLock ); } while( 0 )
#else
#   define InitPrintfLock() ((void)0)
#endif

static void PhilosopherThreadProc( void *ud )
{
    int i = (int) ud;
    
    MPLock left = chopsticks[i - 1];
    MPLock right = chopsticks[i % PHILOSOPHER_COUNT];
    
    printf( "Philosopher %d sitting down\n", i );
    while (running) {
        printf( "Philosopher %d thinking...\n", i );
        RandomSleep( 500, 2000 );
        if (!running) break;

        printf( "Philosopher %d getting hungry, grabbing chopsticks\n", i );
        
        MPAquireLock(  left );
        printf( "Philosopher %d grabbed left chopstick\n", i );
        
        MPAquireLock( right );
        printf( "Philosopher %d grabbed right chopstick, starting to eat\n", i );
        
        ++timesEaten[i - 1];
        RandomSleep( 1000, 3000 );
        
        printf( "Philosopher %d is done eating, putting down chopsticks\n", i );
        MPReleaseLock( left );
        MPReleaseLock( right );
    }
    printf( "Philosopher %d leaves the table\n", i );
}

int main( int argc, char **argv )
{
    InitPrintfLock();
    
    for (int i = 0; i < PHILOSOPHER_COUNT; i++) {
        MPCreateLock( &chopsticks[i] );
    }
    printf( "Table set, letting philosophers enter\n" );
    for (int i = 0; i < PHILOSOPHER_COUNT; i++) {
        MPStartThread( &threads[i], PhilosopherThreadProc, (void *)(int)(i + 1) );
    }
    
    sleep( 120 );
    
    printf( "Dinner is over\n" );
    running = false;
    
    MPWaitForAllEvents( PHILOSOPHER_COUNT, threads, MP_TIMEOUT_FOREVER );
    
    printf( "All philosophers left\n\n" );
    
    for (int i = 0; i < PHILOSOPHER_COUNT; i++) {
        printf( "Philosopher %d ate %d times\n", i + 1, timesEaten[i] );
    }
    
    return 0;
}